﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Text;

namespace 第七次作业
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void searchButton_Click(object sender, EventArgs e)
        {
            string keyword = keywordTextBox.Text.Trim();
            if (!string.IsNullOrEmpty(keyword))
            {
                await PerformSearches(keyword);
            }
        }

        private async Task PerformSearches(string keyword)
        {
            try
            {
                var tasks = new Task<string>[]
                {
                    SearchEngine("https://www.baidu.com/s?wd=" + keyword),
                    SearchEngine("https://www.bing.com/search?q=" + keyword)
                };

                await Task.WhenAll(tasks);

                baiduResultTextBox.Text = tasks[0].Result;
                bingResultTextBox.Text = tasks[1].Result;
            }
            catch (Exception ex)
            {
                MessageBox.Show("搜索过程中出现错误: " + ex.Message);
            }
        }

        private async Task<string> SearchEngine(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
                string html = await client.GetStringAsync(url);
                string text = Regex.Replace(System.Net.WebUtility.HtmlDecode(html), @"<[^>]+>|&nbsp;", "").Trim();
                return text.Length > 200 ? text.Substring(0, 200) : text;
            }
        }
    }
}

